const async = require("async");
const inquirer = require("inquirer");
const evaluate = require("./evaluate");

module.exports = function ask(prompts, data, callback) {
  // 逐一交互询问（根据用户回答配置初始化项目）
  async.eachSeries(
    Object.keys(prompts),
    (key, next) => {
      prompt(data, key, prompts[key], next);
    },
    callback
  );
};

// 具体询问的操作
const prompt = (data, key, prompt, next) => {
  // 当询问的一项为false时所依赖的其他项不需要询问，data是一个用户交互输入的对象值
  if (prompt.when && !evaluate(prompt.when, data)) {
    return next();
  }
  inquirer
    .prompt([
      {
        type: prompt.type,
        name: key,
        message: prompt.message,
        choices: prompt.choices || [],
      },
    ])
    .then((answers) => {
      // 将答案保存到data对象中
      data[key] = answers[key];
      next();
    });
};
